package filesystem.adapters;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.emf.ecore.EObject;

/**
 * This adapter is common class for other adapters. Main task of it is to
 * monitor changes of the target feature (or "field" in reflection terms) and
 * call {@link #update(EObject)} method in case observable feature (aka field)
 * was changed.
 * 
 * It is also responsible to call {@link #update(EObject)} in case adapter was
 * attached to new target.
 * 
 * @see AdapterImpl
 * @see Adapter
 * 
 * @author Renat Zubairov, Igor Drobiazko
 */
public abstract class AbstractAdapter extends AdapterImpl {

	/**
	 * ID of the feature of interests
	 */
	protected final int featureId;

	/**
	 * Constructor for adapter that will monitor only single feature. Monitored
	 * featureId is passed as parameter.
	 * 
	 * @param featureId -
	 *            ID of the feature of interest for given adapter
	 */
	public AbstractAdapter(int featureId) {
		super();
		this.featureId = featureId;
	}

	/**
	 * This method is called by EMF notification as soon as any property of the
	 * adapted (observed) object is changed.
	 * 
	 */
	public void notifyChanged(Notification msg) {
		super.notifyChanged(msg);
		int feature = msg.getFeatureID(msg.getNotifier().getClass());
		if (feature == featureId && msg.getNotifier() instanceof EObject) {
			update((EObject) msg.getNotifier());
		}
	}

	/**
	 * This method is called when adapter attached to it's target (observable)
	 */
	public void setTarget(Notifier newTarget) {
		super.setTarget(newTarget);
		if (newTarget != null && newTarget instanceof EObject) {
			// Update the label content
			update((EObject) newTarget);
		}
	}

	/**
	 * This method is called when target is changed and/or when
	 * 
	 * @param object
	 */
	protected abstract void update(EObject object);

}